export default {
  data() {
    return {
      startHeight: 0,
      endHeight: 0,
      Loading: false,
      Timer: 0,
      pages: {
        currentPage: 1,
        pageSize: 20,
        total: 10
      },
      Blocks: []
    }
  },
  computed: {
    ParallelChain() {
      return this.$store.getters.isParallelChain
    },
    maxHeight() {
      return this.$store.state.maxHeight
    }
  },
  mounted() {
    this.getLastBlock()
  },
  watch: {
    Loading(val) {
      if (val === false && this.pages.currentPage === 1) {
        this.Timer = setTimeout(() => {
          this.getLastBlock();
        }, 5000);
      }
    }
  },
  methods: {
    // 获取最新区块
    getLastBlock() {
      if (this.Loading) return
      this.Loading = true
      this.Rpc.getLastHeader().then((data) => {
        if (data.error === null) {
          if (data.result.height !== this.endHeight) {
            this.$store.commit('updateMaxHeight', data.result.height)
            this.pages.total = this.maxHeight
            this.getBlocks(this.maxHeight)
            return
          }
          this.Loading = false
        } else {
          this.Loading = false
          this.$notify.warning({
            title: this.$t('components.tip'),
            message: data.error
          })
        }
      })
    },
    // 获取区块列表
    getBlocks(endHeight) {
      this.Loading = true
      // 首次更新
      if (this.endHeight === 0) {
        this.endHeight = endHeight
        this.startHeight = (this.endHeight - this.pages.pageSize + 1) > 0 ? (this.endHeight - this.pages.pageSize + 1) : 0 // 尾页判断
      } else {
        // 非首次请求获取更新的区块
        this.startHeight = this.endHeight + 1
        this.endHeight = this.maxHeight
      }
      this.Rpc.getHeaders(this.startHeight, this.endHeight).then(data => {
        if (data.error === null) {
          let info = data.result.items.reverse()
          if (this.pages.currentPage === 1) {
            this.Blocks = [...info, ...this.Blocks]
            this.Blocks.length = this.pages.pageSize
          } else {
            this.Blocks = info
          }
          this.Loading = false
        } else {
          this.Loading = false
          this.$notify.warning({
            title: this.$t('components.tip'),
            message: data.error
          })
        }
      })
    },
    pageChange(page) {
      clearTimeout(this.Timer)
      this.pages.currentPage = page
      let newHeight = this.maxHeight - (this.pages.currentPage - 1) * this.pages.pageSize
      this.endHeight = 0
      this.Blocks = []
      this.getBlocks(newHeight)

    },
    sizeChange(size) {
      this.pages.pageSize = size;
      this.pageChange(1)
    }
  },
  beforeDestroy() {
    //清除定时器
    clearTimeout(this.Timer);
  }
}